package com.kizuki.controller;

import com.kizuki.config.ConfirmConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@RequestMapping("confirm")
@RestController
@Api(tags = "发布确认高级",description = "无法消费时备份队列")
public class ConfirmController {

    @Resource(name = "confirmRabbitTemplate")
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MyCallBack myCallBack;

    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback(myCallBack);
        /**
         * true：
         * 交换机无法将消息进行路由时，会将该消息返回给生产者
         * false：
         * 如果发现消息无法进行路由，则直接丢弃
         */
        rabbitTemplate.setMandatory(true);
        //设置回退消息交给谁处理
        rabbitTemplate.setReturnsCallback(myCallBack);
    }

    @ApiOperation("当消息无法消费的时候，备份队列和警告")
    @GetMapping("sendMsg/{message}")
    public void sendMsg(@PathVariable String message) {
        log.info("当前时间：{},发送一条信息给确认发布队列:{}", new Date(), message);
        String key1 = "key1";
        String key2 = "key2";
        CorrelationData data1 = new CorrelationData(key1);
        CorrelationData data2 = new CorrelationData(key2);
        rabbitTemplate.convertAndSend(ConfirmConfig.CONFIRM_EXCHANGE_NAME, key1, message + key1, data1);
        // 即使没有这个routeKey也能发布成功, 只是会丢弃该信息，需要重写RabbitTemplate.ReturnsCallback来输出丢弃消息的信息
        rabbitTemplate.convertAndSend(ConfirmConfig.CONFIRM_EXCHANGE_NAME, key2, message + key2, data2);
    }

}
